// wind_speed_monitor/frontend/js/app.js
document.addEventListener('DOMContentLoaded', function() {
    // API基础URL
    const API_BASE_URL = 'http://127.0.0.1:5000/api';
    let socket = null;

    // 全局数据存储
    const appData = {
        stations: {},
        stationData: {},
        currentStation: 'A',
        threshold: 12.0,
        timeRange: '24h',
        refreshInterval: 30000 // 30秒刷新间隔
    };

    // 初始化页面
    initApp();

    // 主要初始化函数
    async function initApp() {
        try {
            // 1. 获取所有站点信息
            await loadStations();
            
            // 2. 获取阈值
            await getThreshold();
            
            // 3. 加载当前站点数据
            await loadStationData(appData.currentStation);
            
            // 4. 设置WebSocket连接
            setupWebSocket();
            
            // 5. 设置事件监听器
            setupEventListeners();
            
            // 6. 更新UI
            updateUI();
        } catch (error) {
            console.error('初始化应用失败:', error);
            // 如果API请求失败，尝试使用本地存储的数据
            if (localStorage.getItem('windSpeedData')) {
                console.log('使用本地缓存数据');
                appData.stationData = JSON.parse(localStorage.getItem('windSpeedData'));
                updateUI();
            } else {
                // 如果没有本地数据，使用模拟数据
                console.log('生成模拟数据');
                generateMockData();
                updateUI();
            }
        }
    }

    // 加载所有站点信息
    async function loadStations() {
        const response = await fetch(`${API_BASE_URL}/stations`);
        const result = await response.json();
        
        if (result.success) {
            appData.stations = result.stations;
        } else {
            throw new Error('获取站点信息失败');
        }
    }

    // 获取阈值
    async function getThreshold() {
        const response = await fetch(`${API_BASE_URL}/thresholds`);
        const result = await response.json();
        
        if (result.success) {
            appData.threshold = result.threshold;
        } else {
            // 使用默认阈值
            appData.threshold = 12.0;
        }
    }

    // 设置阈值
    async function setThreshold(value) {
        try {
            const response = await fetch(`${API_BASE_URL}/thresholds`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ threshold: value })
            });
            const result = await response.json();
            
            if (result.success) {
                appData.threshold = result.threshold;
                return true;
            }
            return false;
        } catch (error) {
            console.error('设置阈值失败:', error);
            return false;
        }
    }

    // 加载站点数据
    async function loadStationData(stationId, hours) {
        if (!hours) {
            hours = appData.timeRange === '1h' ? 1 : 
                    appData.timeRange === '24h' ? 24 : 
                    appData.timeRange === '7d' ? 168 : 720;
        }
        
        const response = await fetch(`${API_BASE_URL}/stations/${stationId}/data?hours=${hours}`);
        const result = await response.json();
        
        if (result.success) {
            if (!appData.stationData) appData.stationData = {};
            appData.stationData[stationId] = result.data;
            return result.data;
        } else {
            throw new Error(`获取站点${stationId}数据失败`);
        }
    }

    // 获取多站点对比数据
    async function getComparisonData(stationIds, hours = 24) {
        try {
            const response = await fetch(`${API_BASE_URL}/comparison?stations=${stationIds.join(',')}&hours=${hours}`);
            const result = await response.json();
            
            if (result.success) {
                return result.data;
            } else {
                throw new Error('获取对比数据失败');
            }
        } catch (error) {
            console.error('获取对比数据失败:', error);
            return null;
        }
    }

    // 导出数据
    function exportData(stationId, format = 'csv', hours = 168) {
        window.open(`${API_BASE_URL}/export/${stationId}?format=${format}&hours=${hours}`);
    }

    // 设置WebSocket连接
    function setupWebSocket() {
        try {
            if (socket) {
                socket.disconnect();
            }
            
            socket = io('http://127.0.0.1:5000');
            
            socket.on('connect', () => {
                console.log('WebSocket已连接');
            });
            
            socket.on('disconnect', () => {
                console.log('WebSocket已断开');
            });
            
            // 接收数据更新
            socket.on('data_update', (updates) => {
                console.log('接收到数据更新:', updates);
                
                // 更新站点数据
                for (const [stationId, newData] of Object.entries(updates)) {
                    if (!appData.stationData) appData.stationData = {};
                    if (!appData.stationData[stationId]) appData.stationData[stationId] = [];
                    
                    // 添加新数据点
                    appData.stationData[stationId].push(newData);
                    
                    // 保持7天的数据量
                    if (appData.stationData[stationId].length > 168) {
                        appData.stationData[stationId].shift();
                    }
                }
                
                // 保存到本地存储作为缓存
                localStorage.setItem('windSpeedData', JSON.stringify(appData.stationData));
                
                // 如果更新包含当前站点，刷新UI
                if (updates[appData.currentStation]) {
                    updateUI();
                }
            });
            
            // 接收警报
            socket.on('alert', (alert) => {
                console.log('接收到警报:', alert);
                addAlert(alert);
            });
        } catch (error) {
            console.error('WebSocket连接失败:', error);
        }
    }

    // 添加警报到UI
    function addAlert(alert) {
        const alertsContainer = document.getElementById('alerts');
        if (!alertsContainer) return;
        
        const alertEl = document.createElement('div');
        alertEl.className = `bg-${alert.type === 'danger' ? 'red' : 'yellow'}-500/20 p-3 rounded-lg border-l-4 border-${alert.type === 'danger' ? 'red' : 'yellow'}-500 mb-2`;
        alertEl.innerHTML = `
            <p class="font-medium">${alert.message}</p>
            <p class="text-sm opacity-80">${new Date(alert.timestamp).toLocaleString()}</p>
        `;
        alertsContainer.prepend(alertEl);
        
        // 如果警报过多，移除最旧的
        if (alertsContainer.children.length > 5) {
            alertsContainer.removeChild(alertsContainer.lastChild);
        }
    }

    // 更新UI
    function updateUI() {
        updateCurrentStationData();
        updateAlerts();
    }

    // 更新当前站点数据
    function updateCurrentStationData() {
        if (!appData.stationData || !appData.stationData[appData.currentStation]) return;
        
        const stationData = appData.stationData[appData.currentStation];
        if (stationData.length === 0) return;
        
        const latestData = stationData[stationData.length - 1];
        
        // 更新仪表盘数据
        const elements = {
            windEl: document.getElementById('current-wind'),
            tempEl: document.getElementById('current-temp'),
            humidityEl: document.getElementById('current-humidity'),
            statusEl: document.getElementById('station-status')
        };
        
        if (elements.windEl) elements.windEl.textContent = latestData.windSpeed.toFixed(1) + ' m/s';
        if (elements.tempEl) elements.tempEl.textContent = latestData.temperature.toFixed(1) + ' °C';
        if (elements.humidityEl) elements.humidityEl.textContent = Math.round(latestData.humidity) + ' %';
        
        // 检查是否超过阈值
        if (elements.statusEl) {
            if (parseFloat(latestData.windSpeed) > appData.threshold) {
                elements.statusEl.textContent = '警告';
                elements.statusEl.classList.add('text-red-500');
            } else {
                elements.statusEl.textContent = '正常';
                elements.statusEl.classList.remove('text-red-500');
            }
        }
    }

    // 更新警报
    function updateAlerts() {
        if (!appData.stationData) return;
        
        const alertsContainer = document.getElementById('alerts');
        if (!alertsContainer) return;
        
        alertsContainer.innerHTML = '';
        
        // 检查每个站点是否有超过阈值的风速
        Object.entries(appData.stationData).forEach(([stationId, data]) => {
            if (data.length === 0) return;
            
            const latestData = data[data.length - 1];
            const windSpeed = parseFloat(latestData.windSpeed);
            
            if (windSpeed > appData.threshold) {
                const alert = document.createElement('div');
                alert.className = 'bg-red-500/20 p-3 rounded-lg border-l-4 border-red-500 mb-2';
                alert.innerHTML = `
                    <p class="font-medium">站点${stationId}: 风速超过阈值 (${latestData.windSpeed.toFixed(1)}m/s)</p>
                    <p class="text-sm opacity-80">${formatTimestamp(latestData.timestamp)}</p>
                `;
                alertsContainer.appendChild(alert);
            } else if (windSpeed > appData.threshold * 0.8) {
                const alert = document.createElement('div');
                alert.className = 'bg-yellow-500/20 p-3 rounded-lg border-l-4 border-yellow-500 mb-2';
                alert.innerHTML = `
                    <p class="font-medium">站点${stationId}: 风速接近阈值 (${latestData.windSpeed.toFixed(1)}m/s)</p>
                    <p class="text-sm opacity-80">${formatTimestamp(latestData.timestamp)}</p>
                `;
                alertsContainer.appendChild(alert);
            }
        });
    }

    // 格式化时间戳
    function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
    }

    // 数字补零
    function padZero(num) {
        return String(num).padStart(2, '0');
    }

    // 生成模拟数据
    function generateMockData() {
        appData.stationData = {};
        const now = new Date();
        
        for (const stationId in appData.stations) {
            const data = [];
            for (let i = 168; i >= 0; i--) {
                const timestamp = new Date(now.getTime() - i * 3600000);
                let baseWind = 8;
                if (stationId === 'B') baseWind = 6;
                else if (stationId === 'C') baseWind = 10;
                else if (stationId === 'D') baseWind = 7;
                
                data.push({
                    timestamp: timestamp.toISOString(),
                    windSpeed: baseWind + Math.random() * 4 - 2,
                    temperature: 20 + Math.random() * 10 - 5,
                    humidity: 65 + Math.random() * 30 - 15
                });
            }
            appData.stationData[stationId] = data;
        }
        
        // 保存到本地存储
        localStorage.setItem('windSpeedData', JSON.stringify(appData.stationData));
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 阈值滑块
        const thresholdSlider = document.getElementById('threshold-slider');
        if (thresholdSlider) {
            thresholdSlider.value = appData.threshold;
            document.getElementById('threshold-value').textContent = appData.threshold.toFixed(1) + ' m/s';
            
            thresholdSlider.addEventListener('input', function() {
                const value = parseFloat(this.value);
                document.getElementById('threshold-value').textContent = value.toFixed(1) + ' m/s';
                appData.threshold = value;
                
                // 更新阈值到后端
                setThreshold(value);
                
                // 更新警报
                updateAlerts();
            });
        }

        // 时间范围选择
        const timeRange = document.getElementById('time-range');
        if (timeRange) {
            timeRange.value = appData.timeRange;
            
            timeRange.addEventListener('change', async function() {
                appData.timeRange = this.value;
                
                try {
                    await loadStationData(appData.currentStation);
                    updateUI();
                } catch (error) {
                    console.error('加载数据失败:', error);
                }
            });
        }

        // 导出按钮
        const exportBtn = document.getElementById('export-btn');
        if (exportBtn) {
            exportBtn.addEventListener('click', function() {
                const format = document.getElementById('export-format')?.value.toLowerCase() || 'csv';
                const rangeEl = document.getElementById('export-range');
                
                let hours = 168; // 默认7天
                if (rangeEl) {
                    const range = rangeEl.value;
                    if (range === '最近24小时') hours = 24;
                    else if (range === '当前视图数据') {
                        hours = appData.timeRange === '1h' ? 1 : 
                                appData.timeRange === '24h' ? 24 : 
                                appData.timeRange === '7d' ? 168 : 720;
                    }
                }
                
                exportData(appData.currentStation, format, hours);
            });
        }

        // 比较按钮
        const compareBtn = document.getElementById('compare-btn');
        if (compareBtn) {
            compareBtn.addEventListener('click', function() {
                alert('正在开发中: 站点对比功能');
            });
        }
    }

    // 公开方法
    window.app = {
        getStationData: function(stationId) {
            return appData.stationData && appData.stationData[stationId] 
                   ? appData.stationData[stationId] 
                   : [];
        },
        getAllStations: function() {
            return Object.keys(appData.stations);
        },
        getStationInfo: function(stationId) {
            return appData.stations[stationId] || null;
        },
        getCurrentStation: function() {
            return appData.currentStation;
        },
        setCurrentStation: function(stationId) {
            appData.currentStation = stationId;
            loadStationData(stationId).then(() => {
                updateUI();
            }).catch(error => {
                console.error(`加载站点${stationId}数据失败:`, error);
            });
        },
        getCurrentThreshold: function() {
            return appData.threshold;
        },
        setThreshold: function(value) {
            appData.threshold = value;
            setThreshold(value);
            updateAlerts();
            return value;
        },
        exportData: function(format = 'csv', hours = 168) {
            exportData(appData.currentStation, format, hours);
        },
        refreshData: function() {
            loadStationData(appData.currentStation).then(() => {
                updateUI();
            }).catch(error => {
                console.error('刷新数据失败:', error);
            });
        },
        compareStations: async function(stationIds, hours = 24) {
            try {
                return await getComparisonData(stationIds, hours);
            } catch (error) {
                console.error('对比站点失败:', error);
                return null;
            }
        }
    };
});